
<template>
    <ul id="goods">
      <li @click="onClick($event,v.id)" v-for="v in goodsList" :key="v.id">
        <img :src="v.image" alt="">
        <div class="goods-disc">
          {{ v.name  + " "+ v.title}} 
        </div>
        <div class="goods-req">
          <span>限购{{ v.limit}}件</span>
        </div>
        <div class="goods-price">
          <i class="iconfont icon-qianqian-"></i>
          <span>{{ v.price }}</span>
          <span @click.stop="addToCart(v.id,v.title,v.image,v.price)">
            <i class="iconfont icon-cartplus"></i>
          </span>
        </div>
      </li>
      <div style="height: 10rem;width: 10rem;"></div>
    </ul>
</template>
<script>
import {mapState} from 'vuex'

export default {
  name: 'ShowGoods',
  components: {
    
  },
  data() {
    return {
    }
  },
  mounted(){
    this.getGoodsList()
  }, 
  computed:{
  ...mapState('home',['goodsList'])
  },
  // 监视路由的变化
  beforeRouteUpdate(to,from,next){
    // 切换路由则会重新发请求获取数据
    if(to.params.id !== from.params.id){
      this.getGoodsList()
    }
    next()
  },
  methods:{
    onClick($event,id){
      this.$router.push({name:'detail',params:{id}})
    },
    //获取商品信息
    getGoodsList(){
      // 每次匹配到该路由都会传递不同的id值，以此获取不同的商品列表
      const id = this.$route.params.id
      this.$store.dispatch('home/getGoodsList',id)
    },
    addToCart(id,title,image,price){
      // 整理好商品数据
      const data = {
        id,
        title,
        price,
        goodsNum:1,
        image
      }
      // 提示添加成功
      this.$notify({type:'success',text:'√ 添加成功'})
      // 将数据存储到vuex、
      this.$store.commit('cart/ADDGOODS',data) 
      
    }
  }
};
</script>
<style lang='less' scoped>
  #goods{
    width: 35.5rem;
    color: black;
    padding: 1rem;
    padding-top: 0rem;
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    li{
      margin-top: 1rem;
      width: 17.2rem;
      border: 0.1rem solid black;
      img{
        width: 17.2rem;
        height: 15rem;
        background-color: blue;
      }
      .goods-disc{
        font-size: 1.5rem;
        height: 4rem;
        margin: 0.5rem;
        margin-top: 0;
      }
      .goods-req{
        font-size: 1rem;
        color: rgb(173, 11, 11);
        font-weight: 100;
        margin: 0.5rem;
        margin-top: 1rem;
        margin-bottom: 1rem;
        span{
          border: 0.1rem solid  rgb(173, 11, 11);
        }
      }
      .goods-price{
        color: rgb(254, 78, 14);
        margin: 0.5rem;
        i{
          &:first-child{
            font-size: 1rem;
          }
          &:last-child{
            font-size: 2.5rem;
            color:  rgb(58, 120, 220);
            margin-left: 7.5rem;
          }
        }
        span{
          font-size: 1.8rem;
          font-weight:600;
          margin-left: 0.5rem;
        }
      }
    }
  }
</style>